package com.system.elastic.service;

import com.alibaba.fastjson.JSON;
import com.system.elastic.goods.feign.GoodFeign;
import com.system.elastic.mapper.SkuInfoMapper;
import com.system.elastic.model.SkuInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SkuInfoService {

    @Autowired
    private GoodFeign goodFeign;
    @Autowired
    private SkuInfoMapper skuInfoMapper;

    public void addAll() {
        //从第1页开始，每页处理500条
        int pageNum=1;
        int size=500;
        //查询所有数量
        Integer count = goodFeign.count();
        //总页数
        int totalPage = count%size==0? count/size : (count/size)+1;

        //分页查询，并将所有数据导入到索引库中
        for (int i = 0; i <totalPage ; i++) {
            List list = goodFeign.list(pageNum, size);

            //将数据转换成List<SkuInfo>
            List<SkuInfo> skuInfos = JSON.parseArray( JSON.toJSONString(list) , SkuInfo.class);

            //规格处理
            for (SkuInfo skuInfo : skuInfos) {
                skuInfoConverter(skuInfo);
            }
            System.out.println("skuInfo:"+ skuInfos);
            skuInfoMapper.saveAll(skuInfos);
            //页数递增
            pageNum++;
        }
    }
    /***
     * 单条索引操作
     * @param type
     * @param skuInfo
     * 1:增加，2：修改，3：删除
     */
    public void modify(Integer type, SkuInfo skuInfo) {
        if(type==1 || type==2){
            //时间转换
            skuInfoConverter(skuInfo);
            //增加数据到索引库
            skuInfoMapper.save(skuInfo);
        }else{
            skuInfoMapper.deleteById(String.valueOf(skuInfo.getId()));
        }
    }

    public Page<SkuInfo> searchPage(Map<String, String> searchMap) {
        //根据开始时间查询   findByBgtime(Dao)
        return skuInfoMapper.findByBgtime(searchMap.get("startTime"), PageRequest.of(pageNumber(searchMap)-1,20));
    }

    public void skuInfoConverter(SkuInfo skuInfo){
        //获取秒杀时间
        Date seckillBegin = skuInfo.getSeckillBegin();
        if(seckillBegin!=null){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyymmddhhmmss");
            String bgtime = simpleDateFormat.format(seckillBegin);
            skuInfo.setBgtime(bgtime);
        }
    }

    public int pageNumber(Map<String, String> searchMap){
        try {
            return Integer.parseInt( searchMap.get("pageNum") );
        } catch (NumberFormatException e) {
            return 1;
        }
    }

}
